<template>
  <div class="container flow-column h100">
    <div class="container-main h100">
      <list-table-new v-bind="tableSetting" ref="klTable"></list-table-new>
    </div>
  </div>
</template>
<script>
import {
  queryOldStatusList,
  confirm,
  isTest,
  logDelete,
} from "@/api/operationManagement/runLog.js";
export default {
  data() {
    return {
      pageName: "开停机日志",
      query: false,
      tableSetting: {
        singleRow: true,
        defaultQueryFirst: false,
        selectionShow: true,
        showCustomBtn: true,
        showFilterBtn: true,
        pageConfig: {
          pageCode: "runLog", //页面标识，用来存储过滤器以及自定义列的时候用
          userId: this.$store.getters.userInfo.id,
        },
        // 搜索框
        searchObj: {
          searchMethod: (params, sortStr) => {
            this.getTableData(params, sortStr);
          },
          queryData: {
            page: 1,
            pageSize: 15,
            equipmentType: "UNIT",
            disSearch: true,
          },
          searchArr: [
            {
              type: "organization",
              label: "设备管理单位",
              model: "deptManageName",
              idsStr: "deptManage",
              placeholder: "请选择或输入",
            },
            {
              type: "majorEquipment",
              label: "设备名称",
              model: "equipmentName",
              idsStr: "equipmentId",
              placeholder: "请选择或输入",
            },
            {
              type: "select",
              label: "操作类型",
              model: "operateType",
              option: this.$store.getters["dirtData"]("dispatch_operate_type"),
            },
            {
              type: "datetimerange",
              label: "操作时间",
              model: "estimatedTime",
            },
            {
              type: "userOnly",
              label: "操作人",
              model: "operateUserMan",
              placeholder: "请选择或输入",
            },
            {
              type: "input",
              label: "操作原因",
              model: "content",
              placeholder: "请输入",
            },
            {
              type: "userOnly",
              label: "创建人",
              model: "createByName",
              placeholder: "请选择或输入",
            },
            {
              type: "datetimerange",
              label: "创建时间",
              model: "createTime",
            },
            {
              type: "select",
              label: "确认状态",
              model: "isConfirm",
              multiple: true,
              option: this.$store.getters["dirtData"]("operation_log_confirm"),
            },
            {
              type: "select",
              label: "计划类型",
              model: "inPlan",
              multiple: false,
              option: this.$store.getters["dirtData"]("operation_plan_type"),
            },
          ],
        },
        tableDataObj: {
          tableArr: [],
          total: null,
        },
        // 过滤器的值
        filterFormData: {},
        // 过滤器的默认值
        defaultFilterData: {},
        userCustomData: [],
        // 操作按钮
        actionList: [
          // {
          //   name: "确认",
          //   icon: "icon-tijiao",
          //   disabled: !this.$store.getters.isBtnAuth("confirm"),
          //   content: "未授权的功能",
          //   method: () => {
          //     let selectData = this.$refs.klTable.getSelectData();
          //     let flag = selectData.findIndex((item) => {
          //       return item.operateType == "DOWN_FAIL";
          //     });
          //     if (flag == -1) {
          //       this.toChange("confirm", "list");
          //     } else {
          //       this.$message.warning(
          //         "停机不成功不允许确认,请先去详情页面修改操作类型。"
          //       );
          //     }
          //   },
          // },
          // {
          //   name: "试机",
          //   icon: "icon-shiji",
          //   disabled: !this.$store.getters.isBtnAuth("commissioning"),
          //   content: "未授权的功能",
          //   method: () => {
          //     let selectData = this.$refs.klTable.getSelectData();
          //     let flag = selectData.findIndex((item) => {
          //       return item.operateType == "DOWN_FAIL";
          //     });
          //     if (flag == -1) {
          //       this.toChange("test", "list");
          //     } else {
          //       this.$message.warning(
          //         "停机不成功不允许试机,请先去详情页面修改操作类型。"
          //       );
          //     }
          //   },
          // },
          // {
          //   name: "删除",
          //   icon: "icon-shanchu",
          //   disabled: !this.$store.getters.isBtnAuth("delete"),
          //   content: "未授权的功能",
          //   method: () => {
          //     this.toChange("delete", "list");
          //   },
          // },
          {
            name: "导出",
            icon: "icon-daochu",
            disabled: !this.$store.getters.isBtnAuth("export"),
            content: "未授权的功能",
            method: () => {
              this.goExport();
            },
          },
        ],
        // 表头
        column: [
          {
            label: "设备管理单位",
            prop: "deptManageName",
            sortable: true,
          },
          {
            label: "设备名称",
            prop: "equipmentName",
            sortable: true,
          },
          {
            label: "计划类型",
            prop: "inPlan",
            sortable: true,
            scopeType: "formate",
            width: "102px",
            method: (row) => {
              let types = this.$store.getters["dirtData"](
                "operation_plan_type"
              );
              let val = row.inPlan;
              let obj = types.find((i) => i.value == val);
              return obj ? obj.label : val;
            },
          },
          {
            label: "操作类型",
            prop: "operateType",
            sortable: true,
            width: "135px",
            scopeType: "formate",
            method: (row) => {
              let types = this.$store.getters["dirtData"](
                "dispatch_operate_type"
              );
              let val = row.operateType;
              let obj = types.find((i) => i.value == val);
              obj = obj ? obj.label : val;
              if (obj == "开机成功") {
                return `<span style="display: block; width: 115px; height: 30px; line-height: 30px; border-radius: 5px; text-align: center;  color: rgb(53, 137, 255)">开机成功</span>`;
              } else if (obj == "停机成功") {
                return `<span style="display: block; width: 115px; height: 30px; line-height: 30px; border-radius: 5px; text-align: center;  color: rgb(91, 187, 48)">停机成功</span>`;
              } else {
                return `<span style="display: block; width: 115px; height: 30px; line-height: 30px; border-radius: 5px; text-align: center;  color: rgb(239, 84, 89)">${obj}</span>`;
              }
            },
          },
          {
            label: "操作时间",
            prop: "operateTime",
            sortable: true,
          },
          {
            label: "操作人",
            prop: "operateUserMan",
            width: "90px",
            sortable: true,
          },
          {
            label: "操作原因",
            prop: "content",
            sortable: true,
          },
          {
            label: "创建人",
            prop: "createByName",
            width: "90px",
            sortable: true,
          },
          {
            label: "创建时间",
            prop: "createTime",
            sortable: true,
          },
          {
            label: "确认状态",
            prop: "isConfirm",
            sortable: true,
            scopeType: "formate",
            method: (row) => {
              if (row.isConfirm == 0) {
                if (row.isErr) {
                  // 异常
                  return `<span title="数据异常，请核对" style="color: rgb(230,0,8)">未确认 ⊗</span>`;
                } else {
                  return `<span style="color: rgb(230,0,8)">未确认</span>`;
                }
              } else if (row.isConfirm == 1) {
                return `<span>已确认</span>`;
              } else if (row.isConfirm == 2) {
                return `<span">待批复</span>`;
              } else if (row.isConfirm == 4) {
                return `<span">作废</span>`;
              } else {
                return `<span style="color: red">错误数据</span>`;
              }
            },
          },
          {
            label: "试机状态",
            prop: "isConfirm",
            sortable: true,
            scopeType: "formate",
            method: (row) => {
              if (row.isTest) {
                return `<span style="color: rgb(240,136,28)">试机</span>`;
              } else {
                return `<span style="color: #000">-</span>`;
              }
            },
          },
          {
            label: "操作",
            type: "button",
            scopeType: "textButton",
            width: "180px",
            buttonArr: [
              {
                text: "确认",
                isShow: (row) => {
                  return (
                    row.isConfirm == 0 &&
                    !row.isTest &&
                    (row.operateType == "START_UP" ||
                      row.operateType == "SHUT_DOWN")
                  );
                },
                methods: (row) => {
                  if (row.operateType == "DOWN_FAIL") {
                    this.$message.warning(
                      "停机不成功不允许确认,请先去详情页面修改操作类型。"
                    );
                  } else {
                    this.toChange("confirm", row.id);
                  }
                },
              },
              {
                text: "试机",
                isShow: (row) => {
                  return (
                    row.isConfirm == 0 &&
                    !row.isTest &&
                    (row.operateType == "START_UP" ||
                      row.operateType == "SHUT_DOWN")
                  );
                },
                methods: (row) => {
                  if (row.operateType == "DOWN_FAIL") {
                    this.$message.warning(
                      "停机不成功不允许试机,请先去详情页面修改操作类型。"
                    );
                  } else {
                    this.toChange("test", row.id);
                  }
                },
              },
              {
                text: "删除",
                isShow: (row) => {
                  return (
                    row.isConfirm == 0 &&
                    !row.isTest &&
                    (row.operateType == "START_UP" ||
                      row.operateType == "SHUT_DOWN")
                  );
                },
                methods: (row) => {
                  this.toChange("delete", row.id);
                },
              },
              {
                text: "详情",
                isShow: () => {
                  return true;
                },
                methods: (row) => {
                  // 未确认 unconfirmed 已确认 confirmed 试机 commissioning 待批复 approved
                  let pageType = "";
                  // if (row.isTest) {
                  //   pageType = "commissioning";
                  // } else {
                  //   if (row.isConfirm == 0) {
                  //     pageType = "unconfirmed";
                  //   } else if (row.isConfirm == 1) {
                  //     pageType = "confirmed";
                  //   } else if (row.isConfirm == 2) {
                  //     pageType = "approved";
                  //   }
                  // }
                  this.getDetails(pageType, row.id);
                },
              },
            ],
          },
        ],
        selectableMethod: (row, rowIndex) => {
          if (row.isConfirm == 0 && !row.isTest) {
            return true;
          } else {
            return false;
          }
        },
        // 表格方法
        tableMethods: {
          //点击行的方法
          rowClick: (val) => {},
        },
      },
      searchQueryData: {}
    };
  },
  created() {
    let query = JSON.parse(JSON.stringify(this.$route.query));
    if (JSON.stringify(query) != "{}") {
      this.tableSetting.defaultQueryFirst = true;
      if (query.minOperateTime) {
        query.minOperateTime =
          this.setData(query.minOperateTime.split(" ")) + "00:00";
      }
      if (query.maxOperateTime) {
        query.maxOperateTime =
          this.setData(query.maxOperateTime.split(" ")) + "23:59";
      }
      query.estimatedTime = [query.minOperateTime, query.maxOperateTime];
      this.$route.hash
        ? (query.equipmentName = decodeURI(this.$route.hash))
        : "";
      this.tableSetting.searchObj.queryData = Object.assign(
        this.tableSetting.searchObj.queryData,
        query
      );
    }
    /* 添加监听事件 */
    window.addEventListener("storage", this.updateData);
  },
  beforeDestroy() {
    /* 删除监听事件 */
    window.removeEventListener("storage", this.updateData);
  },
  mounted() {
    this.$refs.klTable.getTableConfig();
    this.updateData();
  },
  methods: {
    // 处理日期
    setData(data) {
      let year = data[5] || "";
      let month = data[1] || "";
      let day = data[2] || "";
      switch (month) {
        case "Jan":
          month = "01";
          break;
        case "Feb":
          month = "02";
          break;
        case "Mar":
          month = "03";
          break;
        case "Apr":
          month = "04";
          break;
        case "May":
          month = "05";
          break;
        case "Jun":
          month = "06";
          break;
        case "Jul":
          month = "07";
          break;
        case "Aug":
          month = "08";
          break;
        case "Sep":
          month = "09";
        case "Sept":
          month = "09";
          break;
        case "Oct":
          month = "10";
          break;
        case "Nov":
          month = "11";
          break;
        case "Dec":
          month = "12";
          break;
      }
      let times = year + "-" + month + "-" + day + " ";
      return times;
    },
    //更新列表页的数据
    updateData() {
      this.$refs.klTable.searchData();
    },
    // 查询表格数据
    async getTableData(params, sortStr) {
      this.query = params;
      let queryData = {
        page: params.page,
        pageSize: params.pageSize,
      };
      if (params.deptManage) {
        queryData.deptManage = params.deptManage;
      }
      if (params.deptManageName) {
        queryData.deptManageName = params.deptManageName;
      }
      if (params.equipmentId) {
        queryData.equipmentId = params.equipmentId;
      }
      if (params.equipmentName) {
        queryData.equipmentName = params.equipmentName;
      }
      if (params.operateType) {
        queryData.operateType = params.operateType;
      }
      if (params.estimatedTime) {
        queryData.minOperateTime = params.estimatedTime[0];
        queryData.maxOperateTime = params.estimatedTime[1];
      }
      if (params.operateUserMan) {
        queryData.operateUserMan = params.operateUserMan;
      }
      if (params.content) {
        queryData.content = params.content;
      }
      if (params.createByName) {
        queryData.createByName = params.createByName;
      }
      if (params.createTime) {
        queryData.startCreateTime = params.createTime[0];
        queryData.endCreateTime = params.createTime[1];
      }
      if (params.isConfirm) {
        queryData.isConfirm = params.isConfirm;
      }
      if (params.inPlan) {
        queryData.inPlan = params.inPlan;
      }
      if (sortStr.length > 0) {
        queryData.orders = sortStr;
      }
      this.searchQueryData = queryData
      let { data } = await queryOldStatusList(queryData);
      this.$set(this.tableSetting, "tableData", data.list || []);
      this.$set(this.tableSetting, "totalNumber", data.total || 0);
    },
    // 确认、试机、删除
    toChange(type, id) {
      let typeText = "";
      let actionApi = () => {};
      if (type == "confirm") {
        typeText = "确认";
        actionApi = (params) => {
          return confirm(params);
        };
      } else if (type == "test") {
        typeText = "试机";
        actionApi = (params) => {
          return isTest(params);
        };
      } else {
        typeText = "删除";
        actionApi = (params) => {
          return logDelete(params);
        };
      }
      this.$confirm(`是否将数据${typeText}`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          let val = {};
          let list = [];
          let selectData = [];
          if (id == "list") {
            selectData = this.$refs.klTable.getSelectData();
            selectData.forEach((item) => {
              list.push(item.id);
            });
          } else {
            list.push(id);
          }
          if (type == "confirm") {
            // 确认
            val = {
              isConfirm: 1,
              list,
            };
          } else if (type == "test") {
            // 试机
            val = {
              isTest: true,
              list,
            };
          } else {
            // 删除
            val = list;
          }
          actionApi(val).then((res) => {
            if (res.code == 200) {
              if (id == "list") {
                selectData = this.$refs.klTable.getSelectData();
                selectData.forEach((item) => {
                  if (type == "confirm") {
                    // 确认
                    this.$utils.addOperateLog(
                      item.id,
                      `确认了${this.pageName}`
                    );
                  } else if (type == "test") {
                    // 试机
                    this.$utils.addOperateLog(
                      item.id,
                      `试机了${this.pageName}`
                    );
                  } else {
                    // 删除
                    this.$utils.addOperateLog(
                      item.id,
                      `删除了${this.pageName}`
                    );
                  }
                });
              } else {
                if (type == "confirm") {
                  // 确认
                  this.$utils.addOperateLog(id, `确认了${this.pageName}`);
                } else if (type == "test") {
                  // 试机
                  this.$utils.addOperateLog(id, `试机了${this.pageName}`);
                } else {
                  // 删除
                  this.$utils.addOperateLog(id, `删除了${this.pageName}`);
                }
              }
              this.$message.success("操作成功！");
              this.updateData();
            }
          });
        })
        .catch((e) => {});
    },
    // 导出
    async goExport() {
      this.$utils.downloadFile(
        null,
        null,
        "eam-service-operation/startlog/logExport",
        this.searchQueryData
      );
    },
    // 跳转至详情页,携带参数分别为：页面类型、数据id
    getDetails(pageType, id) {
      const { href } = this.$router.resolve({
        name: "runLogDetails",
        query: {
          pageType: pageType,
          id: id,
        },
      });
      window.open(href, "_blank");
    },
  },
};
</script>
<style lang="less" scoped>
.flow-column {
  display: flex;
  flex-flow: column nowrap;
}
</style>